package net.yxsoft.kit;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.enumclass.TsUserTypeEnumCls;
import net.yxsoft.model.infrastructure.TsUser;
import net.yxsoft.quorum.QuorumKit;
import net.yxsoft.resource.AuthuserRes;
import net.yxsoft.resource.Res;
import rapid.core.Authuser;
import rapid.util.DateKit;
import rapid.util.StrKit;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.*;

public class Helper {

  public static final Object SYNC_SERIAL_NUMBER = new Object();
  public static final Helper me = new Helper();
  private static SecureRandom secureRandom = new SecureRandom();

  /**
   * 处理查询条件为文本框输入的字符串，处理空格情况，解析成并且关系
   * mlb
   */
  public static String getVagueQuery(String value, String field, boolean isPrefix) {
    if(StrKit.isEmpty(value.replace("'", "")) || StrKit.isEmpty(field)) {
      return "";
    }
    value = StrKit.strFilter(value);  //过滤sql关键字和特殊符号
    StringBuilder _sqlStr = new StringBuilder();
    value = value.replace("'", "").replace(" ", " ");
    String _sqlArray[] = value.split(" ");
    int _arrLen = _sqlArray.length;
    for(int i = 0; i < _arrLen; i++) {
      if(i == 0) {
        _sqlStr.append(String.format(" INSTR(%s,'%s')<>0 ", field, _sqlArray[i]));
      } else {
        _sqlStr.append(String.format(" AND INSTR(%s,'%s')<>0 ", field, _sqlArray[i]));
      }
    }

    if(isPrefix) {
      _sqlStr.insert(0, " AND ");
    }

    return _sqlStr.toString();
  }

  public static Map<String, Object> setUserResource(Map<String, Object> rs, Authuser user) {
    rs.put("USER_TYPES", TsUserTypeEnumCls.LIST_DEFAULT);

    rs.put("GROUP_ROOT_CODE", Res.GROUP_ROOT_CODE);
    rs.put("GROUP_ROOT_NAME", Res.GROUP_ROOT_NAME);
    rs.put("GROUP_ROOT_ID", Res.groupRootId);

    rs.put("USER_ID", user.getLoginId());
    rs.put("USER_NAME", user.getName());
    TsUserTypeEnumCls utype = user.get(AuthuserRes.KEY_TYPE);

    if(utype == null) {
      rs.put("USER_TYPE", null);
    } else {
      rs.put("USER_TYPE", utype.getValue());
    }
    rs.put("USER_PHONE", user.get(AuthuserRes.KEY_PHONE));

    rs.put("USER_GROUPS", user.get(AuthuserRes.KEY_GROUPS));
    String groupIds = user.get(AuthuserRes.KEY_GROUP_IDS);
    rs.put("USER_GROUP_IDS", groupIds);
    rs.put("USER_GROUP_NAMES", user.get(AuthuserRes.KEY_GROUP_NAMES));
    rs.put("USER_HAS_ROOT_GROUP", user.get(AuthuserRes.KEY_HAS_ROOT_GROUP));

    return rs;
  }

  public static String getField(int num) {
    return "attrib_" + StrKit.padLeft(Integer.toString(num), 2, "0");
  }

  /**
   * 生成|更新序号(s_serial_number表)
   *
   * @param type
   * @return
   */
  public static String updateSerialNumberByDate(Date date, String type) {
    synchronized(SYNC_SERIAL_NUMBER) {
      Record rd = Db.findFirst("select attrib_01, attrib_14, attrib_17 from s_serial_number where attrib_01 = ?", type);

      String serialNum;

      if(rd == null) {
        // 初始化一条序号记录
        serialNum = "1";
        CustomDb.updateWithExceptionHandling("insert into s_serial_number (attrib_01, attrib_14, attrib_17) values (?, Date(NOW()), ?)", type, serialNum);

      } else {
        Date lastDt = rd.getDate("attrib_14");
        String dstr = DateKit.format(date, "yyyyMMdd");

        if(!dstr.equals(DateKit.format(lastDt, "yyyyMMdd"))) {
          serialNum = "1";

        } else {
          serialNum = Integer.toString(rd.getBigDecimal("attrib_17").intValue() + 1);
        }

        // 更新序号
        CustomDb.updateWithExceptionHandling("update s_serial_number set attrib_14 = Date(NOW()), attrib_17 = ? where attrib_01 = ?", serialNum, type);
      }

      return serialNum;
    }
  }

  /**
   * 生成UUID
   */
  public static  String bulidUUID(){
    UUID uuid = UUID.randomUUID();
    return uuid.toString().replaceAll("-","");
  }



  /**
   * 生成BigIntegerUUID
   */
  public static  BigInteger bulidUUIDBigInteger(){
    long timestamp = Instant.now().toEpochMilli();
    int randomInt = secureRandom.nextInt();
    int uniqueInt = (int)(timestamp ^ randomInt);

    byte[] bytes = BigInteger.valueOf(uniqueInt).toByteArray();
    BigInteger bigInt = new BigInteger(1, bytes); // 1表示非负数
    return bigInt;
  }



}
